<?php
/**
 * 常用类
 * 
 * @author ShuangYa
 * @package EUser
 * @category Library
 * @link http://www.sylingd.com/
 */

namespace euser\libs;
use \Sy;

class Common {
	/**
	 * 判断是否为POST请求
	 * @access public
	 * @return boolean
	 */
	public static function isPost() {
		return ($_SERVER['REQUEST_METHOD'] === 'POST')?TRUE:FALSE;
	}
	/**
	 * 判断是否为PJAX请求
	 * @access public
	 * @return boolean
	 */
	public static function isPjax() {
		return isset($_SERVER['HTTP_X_PJAX']);
	}
	/**
	 * 判断是否为AJAX请求
	 * @access public
	 * @return boolean
	 */
	public static function isAjax() {
		return (isset($_SERVER['HTTP_X_AJAX']) || isset($_REQUEST['ajax']));
	}
	/**
	 * 显示JSON返回结果
	 * @access public
	 * @param array $arr
	 */
	public static function getAjax($arr = []) {
		if (isset($arr['error'])) {
			$arr['success'] = 0;
		} else {
			$arr['success'] = 1;
		}
		return json_encode($arr);
	}
	/**
	 * 获取随机字符串
	 * @param int $length 长度
	 * @param boolean $a 是否包括易混淆的字符串（用于验证码）
	 * @return string
	 */
	public static function getRandStr($length, $a = TRUE) {
		if ($a) {
			$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		} else {
			$str = 'abcdefghjkmnpqrstwxyzABCDEFGHJKLMNPQRSTWXY3456789';
		}
		while (strlen($str) < $length) {
			$str .= $str;
		}
		$str = str_shuffle($str);
		return substr($str, 0, $length);
	}
	/**
	 * 读写配置
	 * 可使用批量写入，用法类似于：option(['key1' => 'val1', 'key2' => 'val2'])
	 * @access public
	 * @param string $key
	 * @param mixed $val
	 * @return mixed
	 */
	public static function option($key, $val = NULL) {
		static $config = NULL;
		if ($config === NULL) {
			$config = require(Sy::$appDir . 'data/config.php');
		}
		if (NULL === $val && is_string($key)) {
			//读取配置
			return isset($config[$key]) ? unserialize($config[$key]) : NULL;
		} elseif (is_array($key)) {
			//批量写入配置
			$config = array_merge($config, $key);
			file_put_contents(Sy::$appDir . 'data/config.php', '<?php' . "\n" . 'return unserialize(\'' . serialize($config) . '\');');
		} else {
			//写入单个配置
			$config[$key] = serialize($val);
			file_put_contents(Sy::$appDir . 'data/config.php', '<?php' . "\n" . 'return unserialize(\'' . serialize($config) . '\');');
		}
	}
}